package com.sunway.android.utils;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.graphics.Bitmap;

public class AsyncImageLoader {
	private Map<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();

	public Bitmap loadDrawable(final String imageUrl,
			final ImageCallback callback) {
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
			if (softReference.get() != null) {
				return softReference.get();
			}
		}
		new Thread() {
			public void run() {
				Bitmap bitmap = loadImageFromUrl(imageUrl);
				imageCache.put(imageUrl, new SoftReference<Bitmap>(bitmap));
				callback.imageLoaded(bitmap);
			};
		}.start();

		return null;
	}

	protected Bitmap loadImageFromUrl(String imageUrl) {

		try {
			Bitmap bitmap = DisplayUtil.decodeSampledBitmapFromStream(new URL(
					imageUrl).openStream(), 90, 90);
			return bitmap;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public interface ImageCallback {
		public void imageLoaded(Bitmap bitmap);
	}
}
